/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ar.com.neolokura.travian.helper.user.admin;

import ar.com.neolokura.travian.helper.bo.object.LoginObject;
import ar.com.neolokura.travian.helper.bo.page.LoginPageObject;
import ar.com.neolokura.travian.helper.browser.admin.BrowserAdmin;
import ar.com.neolokura.travian.helper.constant.TravianWebTree;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import org.apache.log4j.Logger;

/**
 *
 * @author gustavo
 */
public class UserAdmin {

    private static Logger logger = Logger.getLogger(UserAdmin.class.getSimpleName());
    private static UserAdmin INSTANCE = null;
    private WebClient webClient;

    // Private constructor suppresses 
    private UserAdmin() {
        BrowserAdmin browserAdmin = BrowserAdmin.getInstance();
        webClient = browserAdmin.getWebClientInstance();
        logger.info(">> UserAdmin started...");
    }

    // creador sincronizado para protegerse de posibles problemas  multi-hilo
    // otra prueba para evitar instanciación múltiple 
    private synchronized static void createInstance() {
        if (INSTANCE == null) {
            INSTANCE = new UserAdmin();
        }
    }

    public static UserAdmin getInstance() {
        if (INSTANCE == null) {
            createInstance();
        }
        return INSTANCE;
    }

    public LoginObject login(String userName, String password) throws Exception {

        if (userName == null || password == null || userName.equals("") || password.equals("")) {
            throw new Exception("No userName or password Parameters are set");
        }

        LoginObject loginObject = new LoginObject();
        loginObject.setUserName(userName);
        loginObject.setPassword(password);

        // Gets Web Client & pages List
        TravianWebTree travianWeb = new TravianWebTree();

        HtmlPage page = webClient.getPage(travianWeb.getLoginPage());

        LoginPageObject pageObject = new LoginPageObject(page);

        pageObject.setUserName(loginObject.getUserName());
        pageObject.setPassword(loginObject.getPassword());

        page = pageObject.getPageBySubmitButton(); // Goes to next page

        return loginObject;
    }

    public Boolean isLogged(boolean isHtmlUnit) throws Exception {

        Boolean isLogged = false;
        String html = "";

        // Gets Web Client & pages List
        TravianWebTree travianWeb = new TravianWebTree();

        if (isHtmlUnit) {
            HtmlPage page = webClient.getPage(travianWeb.getLoginPage());
            html = page.asXml();
            isLogged = html.contains("dorf2.php") && html.contains("karte.php") && html.contains("statistiken.php") && html.contains("berichte.php");
        }
        return isLogged;
    }
    
   
}
